<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <el-input v-model="query.cityName" placeholder="小区名称" clearable/>
        <el-button type="primary" :icon="Search" @click="handleSearch">
        </el-button>
        <el-button @click="handleClear">重置</el-button>
      </div>
      <div class="handle-box">
        <el-button type="primary" :icon="Plus" @click="handleEdit" style="margin-right: 10px">添加</el-button>
        <!--        <el-button type="primary" disabled>批量添加</el-button>-->
<!--        <el-upload-->
        <!--            style="margin-right: 10px"-->
        <!--            class="upload-demo"-->
        <!--            :auto-upload="false"-->
        <!--            :multiple="false"-->
        <!--            :show-file-list="false"-->
        <!--            :accept="'.xls, .xlsx'"-->
        <!--            @change="handleOfUpload"-->
        <!--        >-->
        <!--          <el-button type="primary">批量添加</el-button>-->
        <!--        </el-upload>-->
        <!--        <el-button :disabled="!multipleSelection.length" @click="handleChangeItem(multipleSelection,'batchDel')">批量删除-->
        <!--        </el-button>-->
      </div>
      <el-table
          :data="tableData"
          max-height="calc(100vh - 250px)"
          border
          class="table"
          @selection-change="handleSelectionChange"
          header-cell-class-name="table-header">
<!--        <el-table-column type="selection" width="55"/>-->
        <el-table-column prop="cityName" label="小区名称" align="center"></el-table-column>
        <el-table-column prop="insertTime" label="加入时间" align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="160" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small"
                       @click="handleEdit(scope.$index, scope.row)"
            >编辑
            </el-button>
            <el-button type="danger" size="small"
                       @click="handleChangeItem(scope.row, 'del')">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
            hide-on-single-page
            v-model:current-page="query.page"
            v-model:page-size="query.pageSize"
            background
            :page-sizes="[10, 20, 30, 40, 50, 100, 200]"
            layout="prev, pager, next, jumper, total, sizes"
            :total="pageTotal"
            @current-change="handlePageChange"
            @size-change="handleLimitChange"
        ></el-pagination>
      </div>
    </div>
    <!--    添加/编辑弹框-->
    <el-dialog v-model="dialogVisible" destroy-on-close :title="addVisible ? '添加小区' : '编辑小区'"
               width="50%"
               draggable>
      <el-form
          label-width="auto"
          ref="ruleFormRef"
          :model="editform"
          :rules="rules"
      >
        <el-form-item label="小区名称" prop="cityName">
          <el-input v-model="editform.cityName"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="saveItem(ruleFormRef)">立即提交</el-button>
        <el-button @click="handleEditClear">重置</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="projectIndex">
import {ref, reactive, computed} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {Delete, Edit, CopyDocument, Search, Plus} from '@element-plus/icons-vue';
import type {FormInstance, FormRules} from 'element-plus'
import {ParkingMgt} from "@/api";
import {useRoute, useRouter} from "vue-router"
import useClipboard from 'vue-clipboard3';
import moment from 'moment';
import * as XLSX from 'xlsx/xlsx.mjs';

const $moment = moment
defineExpose({
  $moment
})

const {toClipboard} = useClipboard();
const copy = async (text) => {
  try {
    await toClipboard(text);  //实现复制
    ElMessage.success('复制成功')
  } catch (e) {
    console.error(e);
  }
};

interface TableItem {
  id?: string;
}

const query = reactive({
  cityName: '',
  page: 1,
  pageSize: 10
});

const reset = () => {
  query.cityName = '';
  query.page = 1;
  query.pageSize = 10;
};

const handleOfUpload = (e: any) => {
  console.log(e);
  // debugger
  const file = e.raw;
  const reader = new FileReader();
  reader.readAsBinaryString(file)// 将文件以二进制形式读入页面
  reader.onload = (e) => {
    const data = e.target.result; //读取成功后result中的数据
    const wb = XLSX.read(data, {type: 'binary'});  //以base64方法读取 结果
    const sheetName = wb.SheetNames[0] //是获取Sheets中第一个Sheet的名字
    const sheets = wb.Sheets[sheetName] //wb.Sheets[Sheet名]获取第一个Sheet的数据
    //将数据解析为json字符串
    const dataList2 = JSON.stringify(XLSX.utils.sheet_to_json(sheets))
    const dataList3 = (JSON.parse(dataList2)) //讲json转为 数组的格式 看格式所需

    const cityNames = dataList3.map(item => {
      return {cityName: item.小区名称}
    })

    console.log(cityNames);
    batchAddParking(cityNames, (res: any) => {
      if (res.data.status === 1) {
        addVisible.value = false;
        ElMessage.success(res.data.msg);
        getData();
      } else {
        ElMessage.error(res.data.msg);
      }
    })
    console.log(dataList3);
  };
  // reader.onload = async function (e) {
  //   console.log(e);
  //   // 解析数据
  //   let context = await XLSX.read(e.target.result, {type: "binary"});
  //   //XLSX.utils.sheet_to_json()解析excel，给空的单元格赋值为空字符串
  //   let excel = await XLSX.utils.sheet_to_json(
  //       context.Sheets[context.SheetNames[0]]
  //   );
  //   console.log(excel);
  // };
  // reader.readAsBinaryString(file);
}

const tableData = ref<TableItem[]>([]);
const pageTotal = ref(0);
// 获取表格数据
const getData = () => {
  ParkingMgt.getProjectItemList(query).then((res: any) => {
    tableData.value = res.data.data?.list || [];
    pageTotal.value = res.data.data?.total || res.data.data?.list?.length || 10;
  });
};
const route = useRoute();
if (route.query) {
  for (let i in route.query) {
    if (query.hasOwnProperty(i) && route.query[i] !== undefined) {
      query[i] = route.query[i];
    }
  }
}
getData();

const selectsData: any = ref({});

const multipleSelection = ref<TableItem[]>([])
const handleSelectionChange = (val: TableItem[]) => {
  multipleSelection.value = val
}

const handleSearch = () => {
  getData();
};

const handleClear = () => {
  reset();
  ElMessage.success("重置成功！");
  getData();
};

const handlePageChange = (val: number) => {
  query.page = val;
  getData();
};

const handleLimitChange = (val: number) => {
  query.page = 1;
  query.pageSize = val;
  getData();
};

const editVisible = ref(false);
const addVisible = ref(false);
let editform = reactive<any>(({
  cityName: ''
}));

// const
const handleEdit = (index?: number, row?: any) => {
  if ((index !== undefined) && index > -1) {
    editVisible.value = true;

    for (const key in row) {
      if (row[key] !== undefined && editform.hasOwnProperty(key)) {
        editform[key] = row[key];
      }
    }
    editform.id = row.id;
  } else {
    handleEditClear();
    addVisible.value = true;
  }
};

const handleEditClear = () => {
  for (const key in editform) {
    if (editVisible.value && key === 'id') continue;
    editform[key] = '';
  }
};

const dialogVisible = computed({
  get: () => !!(addVisible.value || editVisible.value),
  set: (val) => {
    addVisible.value = val;
    editVisible.value = val;
  }
});

const siteSelection = computed({
  get: () => {
    if (addVisible.value) {
      return editform.web_ids || []
    } else {
      return {key: editform.web_id}
    }
  },
  set: (val: any) => {
    editform.web_name = '';
    addVisible.value ? (editform.web_ids = val) : (editform.web_id = val.key);
  }
})

const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  cityName: [{
    required: true, message: '请输入小区名称！', trigger: 'blur'
  }]
})

const batchAddParking = (data, callback) => {
  const params = {cityNames: [...data]}
  ParkingMgt.addProjectItem({...params}).then((res: any) => {
    console.log(res, 'res')
    callback(res)
  })
}

const saveItem = async (formEl: FormInstance | undefined) => {
  if (formEl) {
    const valid = await formEl.validate((valid, fields) => valid);
    if (!valid) return;
  }

  let apiFun, params = {}
  if (addVisible.value) {
    apiFun = ParkingMgt.addProjectItem;
    // params = {cityNames: [{cityName: editform.cityName}]}
    params = {...editform}
  } else if (editVisible.value) {
    apiFun = ParkingMgt.updateProjectItem;
    params = {...editform}
  }
  if (!apiFun) return;
  apiFun({...params}).then((res: any) => {
    if (res.data.status === 1) {
      addVisible.value && (addVisible.value = false);
      editVisible.value && (editVisible.value = false);
      ElMessage.success(res.data.msg);
      getData();
    } else {
      ElMessage.error(res.data.msg);
    }
  })
}

const handleChangeItem = (data: any, type: string) => {
  let contTxt = '', themeTxt = '', apiFun: any = '', apiParams: any = {};
  if (type === 'del') {
    contTxt = '删除小区'
    themeTxt = ' ' + data.cityName + ' ';
    apiFun = ParkingMgt.deleteProjectItem;
    apiParams = {id: data.id}
  } else if (type === 'batchDel') {
    contTxt = '删除选中的小区'
    apiFun = ParkingMgt.deleteProjectItem;
    apiParams = {ids: data.map(item => item.id)}
  }
  if (!apiFun) return;
  ElMessageBox.confirm(`确定要${contTxt + themeTxt}吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    apiFun(apiParams).then((res: any) => {
      if (res.data.status === 1) {
        ElMessage.success(res.data.msg);
        getData();
      } else {
        ElMessage.error(res.data.msg);
      }
    })
  })
      .catch(() => {
      });
};

</script>

<style lang="less" scoped>
.handle-box {
  display: flex;
  flex-wrap: wrap;

  :deep(.el-date-editor),
  .el-select,
  .el-input {
    margin-right: 10px;
    min-width: 350px;
    flex: 1;
  }

  :deep(.el-date-editor),
  .el-select,
  .el-input,
  .el-upload,
  .el-button {
    margin-bottom: 10px;
  }

  :deep(.responseTime) {
    margin-right: 10px;
    //min-width: 350px;
    flex: 1;
    display: flex;
    align-items: center;

    .startTime,
    .endTime {
      flex: 1;
      margin-right: 0px;
    }

    .startTime {
      .el-input__wrapper {
        border-radius: 0;
      }
    }

    .endTime {
      .el-input-group__prepend {
        border-radius: 0;
        box-shadow: 0px 0 0 0 var(--el-input-border-color) inset, 0 1px 0 0 var(--el-input-border-color) inset,0 -1px 0 0 var(--el-input-border-color) inset;
      }
    }

  }
}

.el-table {
  .resultItem {
    color: inherit;
    cursor: pointer;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

    &:hover {
      color: #20a0ff;
    }
  }

  :deep(.el-switch__core) {
    width: 55px;
  }

  .btns {
    display: flex;
    justify-content: center;
  }
}

.el-dialog {
  .el-select {
    width: 100%;
  }

  .tip {
    color: red;
  }
}
</style>